package com.yimi.yinhepda.views.dispatch_module;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.pda.ym.entity.response.NoDataResponse;
import com.pda.ym.utils.SysInfo;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.DispactchScanAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.DispactchScanMasterTableDao;
import com.yimi.yinhepda.db.dao.DispactchScanTableDao;
import com.yimi.yinhepda.db.table.DispatchScanMasterTable;
import com.yimi.yinhepda.db.table.DispatchScanTable;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.entity.bean.DispatchEntity;
import com.yimi.yinhepda.entity.request.DispatchUploadRequest;
import com.yimi.yinhepda.entity.request.QueryWaybillByChildNoRequest;
import com.yimi.yinhepda.entity.request.ScanLoadUploadRequest;
import com.yimi.yinhepda.entity.response.CheckWayBillNoStatus;
import com.yimi.yinhepda.entity.response.CheckWayBillNoStatusResponse;
import com.yimi.yinhepda.entity.response.DispatchScanResponse;
import com.yimi.yinhepda.entity.response.DispatchTaskResponse;
import com.yimi.yinhepda.entity.response.QueryWaybillByChildNoResponse;
import com.yimi.yinhepda.entity.response.WaybillInfo;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.yimi.yinhepda.utils.IntentUtils;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.views.load_module.DetailsActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

import static java.util.Collections.sort;

/**
 * 配送扫描界面
 *
 * @author 000432
 */
public class DispatchScanActivity extends BaseActivity {
    /**
     * 标题栏左边
     */
    @Bind(R.id.title)
    TextView mTvTitle;
    /**
     * 标题栏中间
     */
    @Bind(R.id.num)
    TextView mTvNum;
    /**
     * 目的地
     */
    @Bind(R.id.next_station)
    TextView mTvNextStation;
    @Bind(R.id.load_task_listview)
    ListView mListView;

    /**
     * 配送任务号
     */
    private String mTaskNo;
    /**
     * 配送大区code
     */
    private String mBigAreaCode;
    /**
     * 配送区域code
     */
    private String mAreaCode;
    private String mCarNo;
    private String mDestZoneCode;
    private String mBigAreaName;
    /**
     * 所属企业
     */
    private String mToCompCode;
    /**
     * 派送任务集合
     */
    public static List<DispatchEntity> mDispatchDataList = new ArrayList<>();
    /**
     * 适配器
     */
    private DispactchScanAdapter mAdapter;
    /**
     * 数据库
     */
    private DispactchScanTableDao mDispactchScanTableDao;
    private DispactchScanMasterTableDao dispactchScanMasterTableDao;
    /**
     * 当前操作条目
     */
    private TextView totle_weight, totle_volume, totle_piao, totle_jian, hold_weight, hold_volume, hold_piao, hold_jian;

    /**
     * 总的未上传数量
     */
    private int totalNotUploadNum;

    @Override
    public String getPageName() {
        return getString(R.string.page_dispatch_scan);
    }

    public DispatchScanActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dispatch_scan);
        ButterKnife.bind(this);

        initView();
        initEvent();
        initData();
    }

    public void initView() {
        totle_weight = findViewById(R.id.totle_weight);
        totle_volume = findViewById(R.id.totle_volume);
        totle_piao = findViewById(R.id.totle_piao);
        totle_jian = findViewById(R.id.totle_jian);
        hold_weight = findViewById(R.id.hold_weight);
        hold_volume = findViewById(R.id.hold_volume);
        hold_piao = findViewById(R.id.hold_piao);
        hold_jian = findViewById(R.id.hold_jian);
    }

    public void initEvent() {
        findViewById(R.id.load_scan_back).setOnClickListener(this);
        findViewById(R.id.load_scan_refresh_img).setOnClickListener(this);
        findViewById(R.id.load_upload).setOnClickListener(this);
        findViewById(R.id.btn_add).setOnClickListener(this);
        findViewById(R.id.btn_del).setOnClickListener(this);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Intent intent = new Intent(DispatchScanActivity.this, DispatchWayBillDetailActivity.class);
                intent.putExtra(IntentUtils.BUILD_WAYBILLNO, mDispatchDataList.get(position).getWaybillNo() + "");
                startActivityForResult(intent, 0);
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Intent intent = new Intent(DispatchScanActivity.this, DetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("waybill", mDispatchDataList.get(position).getWaybillNo() + "");
                intent.putExtras(bundle);
                startActivity(intent);
                return true;
            }
        });

        mTvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //                startDealScanResult("100000061244001");
            }
        });
    }

    public void initData() {
        EventBus.getDefault().register(this);
        mDispactchScanTableDao = new DispactchScanTableDao();
        dispactchScanMasterTableDao = new DispactchScanMasterTableDao();
        //查询未上传数据
        totalNotUploadNum = mDispactchScanTableDao.queryNotUploadDataNum();
        mTvNum.setText(totalNotUploadNum + "");
        //标题
        mTvTitle.setText(getString(R.string.dispatch_scan));
        //配置单号
        mTaskNo = DispatchTaskActivity.mDispatchTaskEntity.getTaskNo();
        //目的地的
        mBigAreaCode = DispatchTaskActivity.mDispatchTaskEntity.getDispatchBigAreaCode();
        //配送区域code
        mAreaCode = DispatchTaskActivity.mDispatchTaskEntity.getDispatchAreaCode();
        //车牌号
        mCarNo = DispatchTaskActivity.mDispatchTaskEntity.getCarNo();
        //到达网点
        mDestZoneCode = DispatchTaskActivity.mDispatchTaskEntity.getDeptCode();
        //大区名称
        mBigAreaName = DispatchTaskActivity.mDispatchTaskEntity.getDispatchBigAreaName();
        //所属企业
        mToCompCode = DispatchTaskActivity.mDispatchTaskEntity.getCompCode();
        //下一站
        mTvNextStation.setText(mBigAreaName);
        //配送任务详情数据集合
        mDispatchDataList = DispatchTaskActivity.mDispatchTaskEntity.getSoonList();
        if (mDispatchDataList == null) {
            mDispatchDataList = new ArrayList<>();
        }

        showDataDetail();
        //查询上传扫描条数
        Common.queryDictScanUploadNum();
    }

    /**
     * 1.获取网络数据
     */
    public void loadData() {
        setScannerEnabled(false);
        showPgDlg("正在加载...");

        Map param = new HashMap();
        //配送大区code
        param.put("dispatchBigAreaCode", mBigAreaCode);
        if (mAreaCode != null) {
            //配送区域code
            param.put("dispatchAreaCode", mAreaCode);
        }
        param.put("compCode", mToCompCode);
        param.put("destZoneCode", mDestZoneCode);
        //预约开始时间（String）（格式：yyyy-MM-dd HH:mm:ss）
        param.put("subscribeBeginTimeStr", DateHelper.getDateFormate(new Date()) + " 00:00:00");
        //预约结束时间（String）（格式：yyyy-MM-dd HH:mm:ss）
        param.put("subscribeEndTimeStr", DateHelper.getDateFormate(new Date()) + " 23:59:59");

        new NetRequest().setUrl(Constants.URL_DISPATCH_SCAN)
                .setMethod(NetRequest.Method.GET)
                .setParams(param)
                .setResponsClazz(DispatchScanResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("服务器出错了!");
                        }
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        DispatchScanResponse response = (DispatchScanResponse) obj;
                        SoundVibratorManager.playSound(1);
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }
                });
    }

    /**
     * 数据在列表中展示等
     */
    private void showDataDetail() {
        if (mDispatchDataList != null) {
            //获取本地强扫的运单，将其添加至列表中
            List<DispatchScanMasterTable> dispatchScanMasterTableList = dispactchScanMasterTableDao.getWaybillMasterByMaster("2", mTaskNo);
            if (dispatchScanMasterTableList != null) {
                for (DispatchScanMasterTable item : dispatchScanMasterTableList) {
                    DispatchEntity dispatchScanEntity = new DispatchEntity();
                    dispatchScanEntity.setTaskNo(item.getTaskNo());
                    dispatchScanEntity.setWaybillNo(item.getWaybillNo());
                    dispatchScanEntity.setQuantity(item.getQuantity());
                    dispatchScanEntity.setRealWeightQty(Double.parseDouble(item.getRealWeight() + ""));
                    dispatchScanEntity.setMeterageWeightQty(Double.parseDouble(item.getChargeableWeight() + ""));
                    dispatchScanEntity.setRouteCode(item.getRouteCode());
                    dispatchScanEntity.setStoreQuantity(item.getNowInventory());
                    //查询子单
                    List<DispatchScanTable> mScanTableList = mDispactchScanTableDao.findDataByWayBillNo(item.getWaybillNo(), item.getTaskNo());
                    if (mScanTableList != null) {
                        List<DispatchScanResponse.DispatchWaybillChild> childList = new ArrayList<>();
                        for (DispatchScanTable scanTable : mScanTableList) {
                            DispatchScanResponse.DispatchWaybillChild waybillChild = new DispatchScanResponse.DispatchWaybillChild();
                            waybillChild.setChildNo(scanTable.getChildNo());
                            waybillChild.setWaybillNO(scanTable.getWaybillNo());
                            waybillChild.setFlag(1);
                            childList.add(waybillChild);
                        }
                        dispatchScanEntity.setChildList(childList);
                    }
                    mDispatchDataList.add(dispatchScanEntity);
                }
            }

            //创建子单
            for (DispatchEntity entity : mDispatchDataList) {
                if (entity.getChildList() == null) {
                    List<DispatchScanResponse.DispatchWaybillChild> childList = new ArrayList<>();
                    for (int i = 1; i <= entity.getQuantity(); i++) {
                        DispatchScanResponse.DispatchWaybillChild waybillChild = new DispatchScanResponse.DispatchWaybillChild();
                        waybillChild.setChildNo(entity.getWaybillNo() + String.format("%03d", i));
                        waybillChild.setWaybillNO(entity.getWaybillNo());
                        childList.add(waybillChild);
                    }
                    entity.setChildList(childList);
                }
            }

            //查询数据库，是否有当前数据，并改变状态
            justResponseDataStatus(mDispatchDataList);

            //颜色
            Collections.sort(mDispatchDataList);
            if (mAdapter == null) {
                mAdapter = new DispactchScanAdapter(this, mDispatchDataList);
                mListView.setAdapter(mAdapter);
            } else {
                mAdapter.setDataList(mDispatchDataList);
                mAdapter.notifyDataSetChanged();
            }
            //实操票，件等
            showScannedWaybillDetail();
        }
    }

    /**
     * 查询数据库，是否有当前数据，并改变状态
     */
    private void justResponseDataStatus(List<DispatchEntity> mDataList) {

        for (DispatchEntity entity : mDataList) {
            //主单
            Long waybillNo = entity.getWaybillNo();
            //查询数据库对应运单下子单集合
            List<DispatchScanTable> mScanTableList = mDispactchScanTableDao.findDataByWayBillNo(waybillNo, mTaskNo);
            if (mScanTableList != null && mScanTableList.size() > 0) {
                for (DispatchScanTable dispatchScanItem : mScanTableList) {
                    if (dispatchScanItem.getWaybillNo().equals(entity.getWaybillNo())) {
                        for (DispatchScanResponse.DispatchWaybillChild childItem : entity.getChildList()) {
                            if (childItem.getChildNo().equals(dispatchScanItem.getChildNo())) {
                                childItem.setFlag(1);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 刷新
     */
    private void showScannedWaybillDetail() {
        //总票，件等
        totle_piao.setText(String.format("%s", DispatchTaskResponse.getTotalPiaoNum(mDispatchDataList)));
        totle_jian.setText(String.format("%s", DispatchTaskResponse.getTotalJianNum(mDispatchDataList)));
        //总重量，体积
        DecimalFormat df = new java.text.DecimalFormat("#.##");
        totle_weight.setText(df.format(DispatchTaskResponse.getTotalWeight(mDispatchDataList)));
        totle_volume.setText(df.format(DispatchTaskResponse.getTotalVolume(mDispatchDataList)));
        //实操票，件等
        hold_piao.setText(String.format("%s", DispatchTaskResponse.getScannedPiao(mDispatchDataList)));
        hold_jian.setText(String.format("%s", DispatchTaskResponse.getScannedJian(mDispatchDataList)));
        //实总量，体积
        hold_weight.setText(df.format(DispatchTaskResponse.getScannedWeight(mDispatchDataList)));
        hold_volume.setText(df.format(DispatchTaskResponse.getScannedVolume(mDispatchDataList)));
    }

    @Override
    public void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            doScan(result);
        }
    }

    /**
     * 巴枪扫描完成，返回处理条码，刷新列表，显示扫描数量
     */
    private void doScan(final String result) {

        if (!StringUtils.isWaybillNo(result)) {
            showToast("运单号不规范!");
            SoundVibratorManager.playSound(2);
            return;
        }

        /** 条码在任务内*/
        if (mDispatchDataList != null && !mDispatchDataList.isEmpty()) {
            for (int i = 0; i < mDispatchDataList.size(); i++) {
                //运单对象
                DispatchEntity currentItemInfo = mDispatchDataList.get(i);
                /** 判断子单是不是以主单开始的,减少循环次数*/
                if (!result.startsWith(String.valueOf(currentItemInfo.getWaybillNo()))) {
                    continue;
                }
                //子单集合
                List<DispatchScanResponse.DispatchWaybillChild> childList = currentItemInfo.getChildList();

                //循环出单个子单
                for (DispatchScanResponse.DispatchWaybillChild childInfo : childList) {

                    String childWayBillNO = childInfo.getChildNo();
                    /** 扫描的子单发现在任务中*/
                    if (result.equals(childWayBillNO)) {

                        Integer status = childInfo.getFlag();
                        if (status == 1) {
                            SoundVibratorManager.playSound(2);
                            showToast("重复扫描!");
                        } else {

                            /** 扫描数据插入到表中*/
                            if (insertScannedData(null, currentItemInfo, childWayBillNO, "1") < 0) {
                                SoundVibratorManager.playSound(2);
                                showToast("插入数据库失败!");
                                return;
                            }

                            //未上传数据
                            totalNotUploadNum++;
                            mTvNum.setText(totalNotUploadNum + "");
                            EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                            /** 设置该子单为已扫描的状态*/
                            childInfo.setFlag(1);
                            SoundVibratorManager.playSound(1);

                            /** 刷新增加的已扫描票和件*/
                            showScannedWaybillDetail();

                            /** 上传*/
                            //uploadData();
                        }

                        /** 更新当前行到第一行*/
                        mDispatchDataList.remove(i);
                        /**排序按照颜色：红，白，黄，绿*/
                        Collections.sort(mDispatchDataList);
                        mDispatchDataList.add(0, currentItemInfo);
                        /** 刷新列表*/
                        mAdapter.notifyDataSetChanged();
                        return;
                    }
                }
            }
        }

        //该条码不在配载单据内
        //子单下载主单
        //MyDialog dialog = new MyDialog(this);
        //dialog.setIcon(R.drawable.alert);
        //dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        //dialog.setTitle("系统提示");
        //dialog.setMessage("不在该任务下的运单，是否继续？");
        //dialog.setPositiveClickListener(R.drawable.btn_login_selector, "是", new DialogInterface.OnClickListener() {
        //  @Override public void onClick(DialogInterface dialog, int which) {
        //    dialog.dismiss();
        //    //调用接口，判断该运单是否已经预约，没有预约给出相应提示
        //    checkWaybillNoStatus(result);
        //  }
        //});
        //dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", new DialogInterface.OnClickListener() {
        //  @Override public void onClick(DialogInterface dialog, int which) {
        //    dialog.dismiss();
        //  }
        //});
        //dialog.show();
        getWaybillNo(result);
    }


    private void getWaybillNo(final String result) {
        showPgDlg("运单查询中...");
        Map param = new HashMap(1);
        param.put("waybillNo", result.substring(0, 12));
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_DELIVERY_TASK_NO)
                .setParams(param)
                .setResponsClazz(NoDataResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        NoDataResponse response = (NoDataResponse) obj;
                        if (response.getData() != null && !"".equals(response.getData())) {
                            showToast("该运单已在配送任务中：" + response.getData());
                            SoundVibratorManager.playSound(2);
                        } else {
                            downloadWaybillNo(result);
                        }
                    }
                });
    }

    /**
     * 校验运单状态
     */
    private void checkWaybillNoStatus(String result) {
        final String tempResult = result;
        if (result.length() > 12) {
            result = result.substring(0, 12);
        } else if (result.length() != 12) {
            showToast("运单号不规范!");
            SoundVibratorManager.playSound(2);
            return;
        }
        setScannerEnabled(false);
        showPgDlg("正在校验运单...");
        Map param = new HashMap();
        param.put("waybillNo", result);
        param.put("destZoneCode", mDestZoneCode);
        final String finalResult = result;
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_CHECK_ORDER_WAYBILLNO)
                .setParams(param)
                .setResponsClazz(CheckWayBillNoStatusResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        setScannerEnabled(true);
                        dismissPgDlg();
                        if (obj instanceof CheckWayBillNoStatusResponse) {
                            final String subResult = "非今日运单";
                            String resultStr = "";
                            CheckWayBillNoStatusResponse response = (CheckWayBillNoStatusResponse) obj;
                            List<CheckWayBillNoStatus> lists = response.getData();
                            if (lists != null && lists.size() > 0) {
                                CheckWayBillNoStatus entity = lists.get(0);
                                if (entity.getIsDelete() == 1) {
                                    resultStr = "该运单已删除！";
                                } else if (entity.getWaybillFlag() != 0) {
                                    if (entity.getWaybillFlag() == 1) {
                                        resultStr = "该运单已中止！";
                                    } else if (entity.getWaybillFlag() == 2) {
                                        resultStr = "该运单已作废！";
                                    }
                                } else if (entity.getDispatchStatus() == 1) {
                                    resultStr = "该运单已派送未交款！";
                                } else if (entity.getDispatchStatus() == 2) {
                                    resultStr = "该运单已派送已交款！";
                                } else if (entity.getOptionStatus() == 3) {
                                    resultStr = "该运单已更改未审核！";
                                } else if (entity.getSubscribeTime() == null || entity.getSubscribeTime().equals("")) {
                                    resultStr = "该运单未预约！";
                                } else if (entity.getSubscribeTimeStr() != null && !checkTodaySubscribeTime(entity.getSubscribeTimeStr())) {
                                    resultStr = subResult;
                                } else if (entity.getStoreTimeStr() == null
                                        || entity.getStoreTimeStr().equals("")
                                        || entity.getInventoryStatus() == 3
                                        || entity.getInventoryStatus() == 4) {
                                    resultStr = "该运单尚未入库！";
                                }
                            } else {
                                resultStr = "未查询到该运单数据！";
                            }
                            if (resultStr.equals(subResult)) {
                                //非今日运单,提示用户
                                MyDialog dialog = new MyDialog(DispatchScanActivity.this);
                                dialog.setIcon(R.drawable.alert);
                                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                                dialog.setTitle("系统提示");
                                dialog.setMessage("不是预约今日的运单，是否继续");
                                dialog.setPositiveClickListener( "是", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        downloadWaybillNo(tempResult);
                                    }
                                });
                                dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "否", null);
                                dialog.show();
                                SoundVibratorManager.playSound(2);
                            } else if (!resultStr.equals("")) {
                                MyDialog dialog = new MyDialog(DispatchScanActivity.this);
                                dialog.setIcon(R.drawable.alert);
                                dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                                dialog.setTitle("系统提示");
                                dialog.setMessage(resultStr);
                                dialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                dialog.show();
                                SoundVibratorManager.playSound(2);
                            } else {
                                downloadWaybillNo(tempResult);
                            }
                        }
                    }
                });
    }

    /**
     * 校验预约的日期是否是当天的
     *
     * @param subTime 预约时间
     */
    public static boolean checkTodaySubscribeTime(String subTime) {
        String currentDate = DateHelper.getDateFormate(new Date());
        String[] subTimeSplit = subTime.split(" ");
        if (subTimeSplit.length > 0) {
            String subDate = subTimeSplit[0];
            if (subDate.equals(currentDate)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 子单下载主单
     */
    private void downloadWaybillNo(final String result) {
        setScannerEnabled(false);
        showPgDlg("正在子单下载主单...");

        //扫描数据上传完后  调完成任务
        QueryWaybillByChildNoRequest mQueryWaybillByChildNoRequest = new QueryWaybillByChildNoRequest();
        mQueryWaybillByChildNoRequest.setChildWaybillNo(result);

        Map param = new HashMap();
        param.put("childWaybillNo", result);
        new NetRequest().setUrl(Constants.URL_FORCE_SCAN)
                .setParams(param)
                .setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryWaybillByChildNoResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        if (msg != null) {
                            showToast("子单下载主单失败:" + msg);
                        } else {
                            showToast("子单下载主单失败!");
                        }
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        final QueryWaybillByChildNoResponse response = (QueryWaybillByChildNoResponse) obj;
                        //合并数据到内存，并插入当前条码到数据库
                        //路由验证
                        if (!Common.waybillRouteWrong(response.getData().getRouteCode(), mDestZoneCode)) {
                            //合并数据到内存，并插入当前条码到数据库
                            merge(response.getData(), result);
                        } else {
                            MyDialog dialog = new MyDialog(DispatchScanActivity.this);
                            dialog.setIcon(R.drawable.alert);
                            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
                            dialog.setTitle("系统提示");
                            dialog.setMessage("请核对正确目的站是否派送？");
                            dialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    //合并数据到内存，并插入当前条码到数据库
                                    merge(response.getData(), result);
                                }
                            });
                            dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            dialog.show();
                        }
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                    }
                });
    }

    /**
     * 合并数据到内存，并插入当前条码到数据库
     */
    private void merge(WaybillInfo data, String result) {
        //构建数据
        DispatchEntity dispatchScanEntity = new DispatchEntity();
        dispatchScanEntity.setWaybillNo(data.getWaybillNo());
        dispatchScanEntity.setQuantity(data.getQuantity());
        dispatchScanEntity.setStoreQuantity(data.getNowInventory());
        dispatchScanEntity.setRealWeightQty(data.getRealWeight().doubleValue());
        dispatchScanEntity.setVolume(data.getVolume().doubleValue());
        dispatchScanEntity.setMeterageWeightQty(data.getChargeableWeight().doubleValue());
        dispatchScanEntity.setRouteCode(data.getRouteCode());

        List<DispatchScanResponse.DispatchWaybillChild> childList = new ArrayList<>();
        for (int i = 0; i < data.getQuantity(); i++) {
            String childWaybillNo = data.getWaybillNo() + String.format("%03d", i + 1);
            DispatchScanResponse.DispatchWaybillChild mChildInfo = new DispatchScanResponse.DispatchWaybillChild();
            //设置已强扫子单状态
            if (mDispatchDataList != null) {
                for (DispatchEntity entity : mDispatchDataList) {
                    for (DispatchScanResponse.DispatchWaybillChild child : entity.getChildList()) {
                        if (child.getChildNo().equals(childWaybillNo)) {
                            mChildInfo.setWaybillNO(child.getWaybillNO());
                            mChildInfo.setFlag(child.getFlag());
                        }
                    }
                }
            }
            if (result.equals(childWaybillNo)) {
                mChildInfo.setFlag(1);
            }
            mChildInfo.setChildNo(childWaybillNo);
            childList.add(mChildInfo);
        }
        //子单集合加入到运单对象中
        dispatchScanEntity.setChildList(childList);

        //扫描的子单插入到数据库
        if (insertScannedData(data, dispatchScanEntity, result, "2") < 0) {
            SoundVibratorManager.playSound(2);
            showToast("插入数据失败!");
            return;
        }

        //未上传数据
        totalNotUploadNum++;
        mTvNum.setText(totalNotUploadNum + "");
        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));
        SoundVibratorManager.playSound(1);

        Iterator<DispatchEntity> iterator = mDispatchDataList.iterator();
        while (iterator.hasNext()) {
            DispatchEntity entity = iterator.next();
            if (entity.getWaybillNo() == dispatchScanEntity.getWaybillNo()) {
                iterator.remove();
            }
        }

        sort(mDispatchDataList);
        mDispatchDataList.add(0, dispatchScanEntity);
        mAdapter.notifyDataSetChanged();

        /** 刷新增加的已扫描票和件*/
        showScannedWaybillDetail();

        /** 上传*/
        //uploadData();
    }

    /**
     * 插入已经扫描的数据到表中
     *
     * @param currentItemInfo 当前运单号的相关信息
     * @param waybillChildNo  当前子单的相关信息
     */
    private int insertScannedData(WaybillInfo data, DispatchEntity currentItemInfo, String waybillChildNo, String remark) {
        int result = 0;
        if (data != null) {
            //判断主单号不存在则插入主单号
            boolean exitWaybillNo = dispactchScanMasterTableDao.exitDataByWaybillNo(currentItemInfo.getWaybillNo(), mTaskNo);
            if (!exitWaybillNo) {
                try {
                    DispatchScanMasterTable dispatchScanMasterTable = new DispatchScanMasterTable();
                    dispatchScanMasterTable.setTaskNo(mTaskNo);
                    dispatchScanMasterTable.setWaybillNo(data.getWaybillNo());
                    dispatchScanMasterTable.setQuantity(data.getQuantity());
                    dispatchScanMasterTable.setRealWeight(data.getRealWeight());
                    dispatchScanMasterTable.setChargeableWeight(data.getChargeableWeight());
                    dispatchScanMasterTable.setRouteCode(data.getRouteCode());
                    dispatchScanMasterTable.setPackingSpecification(data.getPackingSpecification());
                    dispatchScanMasterTable.setNowInventory(data.getNowInventory());
                    dispatchScanMasterTable.setRemark(remark);
                    dispatchScanMasterTable.setCreateTime(Constants.GetSysTime());
                    result = dispactchScanMasterTableDao.insert(dispatchScanMasterTable);
                    if (result == -1) {
                        showToast("配送主表数据插入失败！");
                        return result;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        boolean flag = mDispactchScanTableDao.exitDataByChildWaybillNo(waybillChildNo, mTaskNo);
        if (flag) {
            return result;
        }

        DispatchScanTable dispatchScanTable = new DispatchScanTable();
        dispatchScanTable.setTaskNo(mTaskNo);
        dispatchScanTable.setWaybillNo(currentItemInfo.getWaybillNo());
        dispatchScanTable.setChildNo(waybillChildNo);
        //强扫标记
        dispatchScanTable.setChildRemark(remark);
        dispatchScanTable.setDispatchArea(currentItemInfo.getDispatchAreaCode());
        dispatchScanTable.setInputType(1);
        dispatchScanTable.setScanTime(Constants.GetScanTime());
        dispatchScanTable.setOperTime(Constants.GetSysTime());
        dispatchScanTable.setIsUpload(0);
        dispatchScanTable.setSacnDeptCode(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));
        dispatchScanTable.setScanEmpCode(SharedPreferUtil.getInstance().getValue(Common.COMP_CODE));
        dispatchScanTable.setUserIp("");
        //配送扫描件数??
        dispatchScanTable.setTaskScanQuantity(currentItemInfo.getTaskScanQuantity());
        try {
            result = mDispactchScanTableDao.insert(dispatchScanTable);
            if (result == -1) {
                showToast("配送表插入数据失败！");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        }
        return result;
    }

    boolean isUploading = false;

    /**
     * 上传数据
     */
    private void uploadData() {
        setScannerEnabled(false);
        if (isUploading) {
            Log.d("tag", "uploadData: 正在上传数据中...");
            return;
        }

        showPgDlg("正在提交...");
        //控制正在上传
        isUploading = true;

        //获取未上传的数据，然后判断
        final List<DispatchScanTable> unUploadList = mDispactchScanTableDao.getUnUploadDataList(mTaskNo);
        if (unUploadList == null || unUploadList.size() <= 0) {
            showToast("没有未上传的数据!");
            isUploading = false;
            dismissPgDlg();
            setScannerEnabled(true);
            return;
        }

        //上传的json对象
        List<DispatchUploadRequest> dispatchUploadRequest = getBuildUploadData(unUploadList);

        new NetRequest().setUrl(Constants.URL_DISPATCH_UPLOAD)
                .setMethod(NetRequest.Method.POST_STRING)
                .setRequestObject(dispatchUploadRequest)
                .setResponsClazz(NoDataResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        isUploading = false;
                        setScannerEnabled(true);
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //更新未上传字段为已上传
                        for (DispatchScanTable itemTable : unUploadList) {
                            itemTable.setIsUpload(1);
                            mDispactchScanTableDao.updataItem(itemTable);
                        }

                        //减少未上传是数量
                        totalNotUploadNum = totalNotUploadNum - unUploadList.size();
                        if (totalNotUploadNum < 0) {
                            totalNotUploadNum = 0;
                        }
                        mTvNum.setText(totalNotUploadNum + "");
                        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));
                        //
                        isUploading = false;
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }
                });
    }

    /**
     * 上传数据的对象
     */
    private List<DispatchUploadRequest> getBuildUploadData(List<DispatchScanTable> unUploadList) {

        List<DispatchUploadRequest> mList = new ArrayList<>();

        for (DispatchScanTable tableItem : unUploadList) {
            DispatchUploadRequest requestItem = new DispatchUploadRequest();
            requestItem.setTaskNo(tableItem.getTaskNo());
            requestItem.setChildNo(tableItem.getChildNo());
            requestItem.setChildRemark(tableItem.getChildRemark());
            requestItem.setDispatchArea(tableItem.getDispatchArea());
            requestItem.setInputType(tableItem.getInputType());
            requestItem.setSacnDeptCode(tableItem.getSacnDeptCode());
            requestItem.setScanEmpCode(tableItem.getScanEmpCode());
            requestItem.setUserIp(tableItem.getUserIp());
            requestItem.setScanTimeStr(tableItem.getScanTime());
            requestItem.setWaybillNo(tableItem.getWaybillNo());
            //集合
            mList.add(requestItem);
        }
        return mList;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent;
        switch (v.getId()) {
            case R.id.load_scan_back:
                finish();
                break;
            case R.id.load_scan_refresh_img:
                //刷新
                flashList();
                break;
            case R.id.load_upload:
                //上传数据，并完成任务
                if (mDispatchDataList == null || mDispatchDataList.size() <= 0) {
                    showToast(getString(R.string.tmp_no_data));
                    return;
                }
                if (!isScanBill()) {
                    showToast(getString(R.string.no_scan_num));
                    return;
                }
                MyDialog myDialog = new MyDialog(DispatchScanActivity.this);
                myDialog.setIcon(R.drawable.alert);
                myDialog.setMessage("提交后将完成派送，是否提交？");
                myDialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //完成扫描
                        completeTask();
                    }
                });
                myDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, null);
                myDialog.show();
                break;
            case R.id.btn_add:
                intent = new Intent(this, DispatchAddByHandActivity.class);
                intent.putExtra(IntentUtils.BUILD_DEST, mDestZoneCode);
                intent.putExtra(IntentUtils.BUILD_DEST_NAME, mBigAreaCode);
                intent.putExtra("taskno", mTaskNo);
                startActivityForResult(intent, 0);
                break;
            case R.id.btn_del:
                intent = new Intent(this, DispatchDeleteByHandActivity.class);
                intent.putExtra(IntentUtils.BUILD_DEST, mDestZoneCode);
                intent.putExtra(IntentUtils.BUILD_DEST_NAME, mBigAreaCode);
                intent.putExtra("taskno", mTaskNo);
                intent.putExtra(IntentUtils.DISPATCH_LIST, (Serializable) mDispatchDataList);
                startActivityForResult(intent, 0);
                break;
            default:
                break;
        }
    }

    /**
     * 刷新列表数据
     */
    private void flashList() {
        showPgDlg("正在刷新...");
        Map param = new HashMap(4);
        param.put("carNo", mCarNo);
        param.put("distrDeptCode", SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));
        //预约开始时间（String）（格式：yyyy-MM-ddTHH:mm:ssZ）格林威治开始时间
//        param.put("subscribeBeginTime", DateHelper.getDateFormate(DateHelper.getOldDate(-1)) + "T16:00:00.000Z");
        //预约结束时间（String）（格式：yyyy-MM-ddTHH:mm:ssZ）格林威治结束时间
//        param.put("subscribeEndTime", DateHelper.getDateFormate(new Date()) + "T15:59:59.084Z");
        new NetRequest().setUrl(Constants.URL_QUERY_TASK_AND_DETAIL)
                .setMethod(NetRequest.Method.GET)
                .setParams(param)
                .setResponsClazz(DispatchTaskResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        if (msg != null) {
                            showToast(msg);
                        } else {
                            showToast("服务器出错了!");
                        }
                        dismissPgDlg();
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        DispatchTaskResponse response = (DispatchTaskResponse) obj;
                        List<DispatchTaskResponse.DispatchTaskEntity> dispatchTaskEntityList = response.getData();
                        if (dispatchTaskEntityList != null) {
                            for (DispatchTaskResponse.DispatchTaskEntity entity : dispatchTaskEntityList) {
                                if (entity.getTaskNo().equals(mTaskNo)) {
                                    mDispatchDataList = entity.getSoonList();
                                    showDataDetail();
                                    break;
                                }
                            }
                        }
                    }
                });
    }

    private boolean isScanBill() {
        for (int i = 0; i < mDispatchDataList.size(); i++) {
            //运单对象
            DispatchEntity currentItemInfo = mDispatchDataList.get(i);
            //子单集合
            List<DispatchScanResponse.DispatchWaybillChild> childList = currentItemInfo.getChildList();
            //循环出单个子单
            if (childList != null) {
                for (DispatchScanResponse.DispatchWaybillChild childInfo : childList) {
                    /** 扫描的单子发现在任务中*/
                    Integer status = childInfo.getFlag();
                    if (status == 1) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private void lastCompleteUpload() {
        //跳转
        Intent intent = new Intent(this, DispatchSuccessActivity.class);
        intent.putExtra("taskno", mTaskNo);
        intent.putExtra("bigArea", mBigAreaName);
        intent.putExtra("carno", mCarNo);
        intent.putExtra("realWeight", DispatchTaskResponse.getScannedWeight(mDispatchDataList) + "");
        intent.putExtra("chargeWeight", DispatchTaskResponse.getScannedChargeableWeight(mDispatchDataList) + "");
        intent.putExtra("totalNotUploadNum", totalNotUploadNum);
        startActivity(intent);
        finish();
    }

    /**
     * 点击提交，完成任务
     */
    private void completeTask() {

        //获取未上传的数据，然后判断
        final List<DispatchScanTable> unUploadList = mDispactchScanTableDao.getUnUploadDataList(mTaskNo);
        if (unUploadList == null || unUploadList.size() <= 0) {
            /** 分页上传扫描数据，然后完成*/
            uploadScanData(unUploadList, null);
            return;
        }

        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在提交扫描数据...");

        //上传的json对象
        List<DispatchUploadRequest> dispatchUploadRequest = getBuildUploadData(unUploadList);

        new NetRequest().setUrl(Constants.URL_DISPATCH_UPLOAD)
                .setMethod(NetRequest.Method.POST_STRING)
                .setRequestObject(dispatchUploadRequest)
                .setResponsClazz(NoDataResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        if (msg.contains("运单号:")) {
                            showError(msg, unUploadList);
                        } else {
                            showToast(msg);
                        }
                        SoundVibratorManager.playSound(2);
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //减少未上传是数量
                        totalNotUploadNum = totalNotUploadNum - unUploadList.size();
                        if (totalNotUploadNum < 0) {
                            totalNotUploadNum = 0;
                        }
                        mTvNum.setText(totalNotUploadNum + "");
                        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                        setScannerEnabled(true);

                        //分页上传扫描表数据
                        uploadScanData(unUploadList, null);
                    }
                });
    }

    /**
     * 上传扫描表数据
     */
    private void uploadScanData(final List<DispatchScanTable> dispatchScanTables, List<UnloadScanTable> records) {
        showPgDlg("上传数据中...");
        if (records != null) {
            //清除缓存中已上传的数据
            Iterator<DispatchScanTable> it = dispatchScanTables.iterator();
            while (it.hasNext()) {
                DispatchScanTable dispatchScanTable = it.next();
                for (UnloadScanTable item : records) {
                    if (item.getChildWaybillNo().equals(dispatchScanTable.getChildNo())) {
                        it.remove();
                        break;
                    }
                }
            }
        }
        //创建扫描上传数据
        records = createScanTableInfo(dispatchScanTables, 0, Common.SCAN_UPLOAD_NUM);
        if (records != null && !records.isEmpty()) {
            ScanLoadUploadRequest request = new ScanLoadUploadRequest();
            request.setRecords(records);
            final List<UnloadScanTable> finalRecords = records;
            new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                    .setResponsClazz(NoDataResponse.class)
                    .setUrl(Constants.UPLOAD_DISPATCH_DATA_URL)
                    .setRequestObject(request)
                    .execute(new UICallBack() {
                        @Override
                        public void onError(String msg) {
                            dismissPgDlg();
                            showToast(msg);
                        }

                        @Override
                        public void onSuccess(Object obj) {
                            try {
                                //更新上传状态
                                for (DispatchScanTable item : dispatchScanTables) {
                                    item.setIsUpload(1);
                                    mDispactchScanTableDao.update(item);
                                }
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }

                            uploadScanData(dispatchScanTables, finalRecords);
                        }
                    });
        } else {
            dismissPgDlg();
            //提交完成跳转
            lastCompleteUpload();
        }
    }

    /**
     * 创建扫描上传数据
     */
    private List<UnloadScanTable> createScanTableInfo(List<DispatchScanTable> dispatchScanTables, int start, int end) {
        List<UnloadScanTable> list = new ArrayList<>();
        List<DispatchScanTable> tempList;
        if (dispatchScanTables.size() >= end) {
            tempList = dispatchScanTables.subList(start, end);
        } else {
            tempList = dispatchScanTables.subList(start, dispatchScanTables.size());
        }
        for (DispatchScanTable item : tempList) {
            UnloadScanTable scanTable = new UnloadScanTable();
            scanTable.setWaybillNo(item.getWaybillNo().toString());
            scanTable.setChildWaybillNo(item.getChildNo());
            scanTable.setStowageNo(item.getTaskNo());
            scanTable.setOperTypeCode(9);
            scanTable.setInputType(1);
            scanTable.setOperEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
            scanTable.setOperEmpName(sharedPreferUtil.getEmpName());
            scanTable.setScanTime(Constants.GetScanTime());
            scanTable.setDeptCode(sharedPreferUtil.getDeptCode());
            scanTable.setDeviceCode(SysInfo.getInstance().getImei());
            scanTable.setDeptType(sharedPreferUtil.getIntValue(Common.DEPT_TYPE));
            scanTable.setWaybillType(1);
            scanTable.setOperPersonCodes(sharedPreferUtil.getValue(Common.USER_CODE));
            list.add(scanTable);
        }
        return list;
    }


    /**
     * 显示错误信息
     */
    private void showError(final String error, final List<DispatchScanTable> unUploadList) {
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setMessage(error);
        dialog.setPositiveClickListener("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                String[] errorSplit = error.split("运单号:");
                String waybillNo = errorSplit[1].substring(0, 12);
                for (DispatchScanTable itemTable : unUploadList) {
                    if (itemTable.getWaybillNo().toString().equals(waybillNo)) {
                        try {
                            mDispactchScanTableDao.delete(itemTable);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        dispactchScanMasterTableDao.deleteByTaskNo(itemTable);
                        break;
                    }
                }
                flashList();
            }
        });
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        //更新实操票，件等
//        showScannedWaybillDetail();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEventBus(CountEvent countEvent) {
        Log.e("", "event---->" + countEvent.getCount());
        mTvNum.setText(countEvent.getCount() + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDispatchDataList != null) {
            mDispatchDataList.clear();
            mDispatchDataList = null;
        }
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            mDispatchDataList.clear();
            mDispatchDataList.addAll((ArrayList<DispatchEntity>) data.getSerializableExtra(IntentUtils.DISPATCH_LIST));
            mAdapter.notifyDataSetChanged();
        }
    }
}
